package ca.kooki.codesnippet.core;

import java.util.ArrayList;
import java.util.List;


public class ActionResponse {

  //```````````````````````
  // STATIC VARIABLES
  //```````````````````````

  private static final String DEFAULT_SUCCESS_MESSAGE_ID = "success";
  private static final String[] EMPTY_ERROR_DATA = new String[0];
  
  //```````````````````````
  // MEMBER VARIABLES
  //```````````````````````

  private List<String> _allErrors;
  private List<String[]> _allErrorsData;
  private String _successMessageId;
  
  //```````````````````````
  // CONSTRUCTOR
  //```````````````````````

  public ActionResponse()
  {
    init();
  }
  
  private void init()
  {
    _allErrors = new ArrayList<String>();
    _allErrorsData = new ArrayList<String[]>();
    _successMessageId = null;
  }
  
  
  //```````````````````````
  // INTERFACE
  //```````````````````````

  public void merge(ActionResponse other)
  {
    _allErrors.addAll(other._allErrors);
    _allErrorsData.addAll(other._allErrorsData);
  }
  
  public void addError(String errorId)
  {
    addError(errorId,EMPTY_ERROR_DATA);
  }
  
  public void addError(String errorId, String[] allErrorData)
  {
    _allErrors.add(errorId);
    _allErrorsData.add(allErrorData);
  }
  
  public boolean isError(String errorId)
  {
    return _allErrors.contains(errorId);
  }
  
  public boolean isError(String errorId, String[] allErrorData)
  {
    int errorIndex = _allErrors.indexOf(errorId);
    if (errorIndex == -1)
    {
      return false;
    }
    
    String[] allActualErrorData = _allErrorsData.get(errorIndex);
    
    if (allActualErrorData.length != allErrorData.length)
    {
      return false;
    }
    
    for (int i=0; i<allActualErrorData.length; i++)
    {
      if (!allActualErrorData[i].equals(allErrorData[i]))
      {
        return false;
      }
    }
    return true;
  }
  
  public boolean isValid()
  {
    return _allErrors.size() == 0;
  }

  public void setSuccessMessage(String messageId)
  {
    _successMessageId = messageId;
  }
  
  public String getMessage() {
    
    if (isValid())
    {
      String messageId = _successMessageId == null ? DEFAULT_SUCCESS_MESSAGE_ID : _successMessageId;
      return Language.getDefault().lookup(messageId);
    }
    else
    {
      StringBuilder builder = new StringBuilder();
      for (int i=0; i<_allErrors.size(); i++)
      {
        String errorId = _allErrors.get(i);
        String[] allErrorData = _allErrorsData.get(i);
        if (i > 0)
        {
          builder.append(",\n");
        }
        builder.append(Language.getDefault().lookup(errorId,false,allErrorData));
      }
      return builder.toString();
    }
    
    
  }
  
}
